<template style='height: 100%'>
  <div id='mysqlList'>
    <!-- 上方按钮 -->
    <div>
      <div style='float: left;'>
        <el-button @click='createInstance' type='primary' size='mini' icon='el-icon-plus'>{{ $t('instance.add') }}
        </el-button>
        <el-button @click='importInstance' type='primary' size='mini'>{{ $t('instance.import') }}</el-button>
        <el-button @click='openDeleteDialog' type='danger' size='mini' icon='el-icon-delete' class='button-margin'>
          {{ $t('instance.delete') }}
        </el-button>
      </div>
    </div>
    <!-- 查询框 -->
    <div style='float: right;'>
      <el-select v-model='filters.searchType' style='width: 105px;' size='mini' @change='changeSearchType'>
        <el-option key='1' :label="$t('instance.instanceName')" value='1'></el-option>
        <el-option key='2' :label="$t('instance.ip')" value='2'></el-option>
      </el-select>
      <el-input :placeholder="$t('instance.placeholder')" v-model.trim='filters.name' clearable size='mini'
                style='width: auto;padding-left: 5px;' v-if='filters.searchType == 1'></el-input>
      <el-input :placeholder="$t('ip.placeholder')" v-model.trim='filters.ipAddress' clearable size='mini'
                style='width: auto;padding-left: 5px;' v-if='filters.searchType == 2'></el-input>
      <el-button @click='clickSearch()' type='primary' size='mini'>{{ $t('instance.search') }}</el-button>
    </div>
    <!-- 表格 -->
    <div style='padding-top: 40px'>
      <table-contain :height.sync="table.maxHeight">
        <el-table :data='tableData' ref='multipleTable' border highlight-current-row slot="table"
                  @selection-change='handleSelectionChange' :height="table.maxHeight">
          <el-table-column type='selection' align='center' width='55'></el-table-column>
          <el-table-column prop='instanceName' :label="$t('instances.instanceName')" min-width='120'
                           show-overflow-tooltip></el-table-column>
          <el-table-column prop='stateName' :label="$t('instances.stateName')" min-width='50'
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-html="getStateIcon(scope.row.state, scope.row.stateName)" style="text-align: center;"></div>
            </template>
          </el-table-column>
          <el-table-column prop='cloudPlatformName' :label="$t('instances.cloudPlatformName')"
                           width='120'></el-table-column>
          <el-table-column prop='instanceChargeTypeName' :label="$t('instances.instanceChargeTypeName')"
                           width='120'></el-table-column>
          <el-table-column prop='regionName' :label="$t('instances.regionName')" min-width='60'
                           show-overflow-tooltip></el-table-column>
          <el-table-column prop='zoneName' :label="$t('instances.zoneName')" min-width='60'
                           show-overflow-tooltip></el-table-column>
          <el-table-column :prop="'engineVersion'" :label="$t('instances.version')" :min-width="60" show-overflow-tooltip>
          </el-table-column>
          <el-table-column :label="$t('instances.operation')" align='center' width='120'>
            <template slot-scope='scope'>
              <el-button size='mini'
                         v-if='checkResourceState(scope.row.state,showdata.start,scope.row.operatingButton,buttonState.start)'
                         type='text'
                         @click='startMysql(scope.row)'>{{ $t('instances.start') }}
              </el-button>
              <el-button size='mini'
                         v-if='checkResourceState(scope.row.state,showdata.stop,scope.row.operatingButton,buttonState.stop)'
                         type='text'
                         @click='stopMysql(scope.row)'>{{ $t('instances.stop') }}
              </el-button>
              <el-button size='mini'
                         v-if='checkResourceState(scope.row.state,showdata.restart,scope.row.operatingButton,buttonState.restart)'
                         type='text'
                         @click='restartMysql(scope.row)'>{{ $t('instances.restart') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination slot='footer' @size-change='handleSizeChange' @current-change='handleCurrentChange'
                       :current-page='currentPage' :page-sizes='[10,20,50,100]' :page-size='pageSize'
                       layout='total, sizes, prev, pager, next' :total='totalSize'>
        </el-pagination>
      </table-contain>
    </div>


    <el-dialog :visible.sync='dialogVisible' title='删除方式'>
      <el-form label-width='80px'>
        <el-form-item>
          <el-radio-group v-model='deleteType' style='margin-left: 20%;'>
            <el-radio v-for='option in options' :label='option.value' :key='option.value'>{{ option.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot='footer' class='dialog-footer'>
        <el-button @click='dialogVisible = false'>取消</el-button>
        <el-button type='primary' @click='clickDelete' style='margin-left: 20px'>确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<style lang='scss'>
@import '../../../assets/iconfont/iconfont.css';
</style>
<script>
import local from './js/local'
import model from '@/public/indexModel.js'
import pubRDSApi from "../../../api/pubRDSApi";
import pubVmUtil from '../vmList/js/pubVmUtil'
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import messageApi from '@/api/messageApi'

export default {
  mixins: [model],
  name: 'pubMysqlList',
  i18n: {
    messages: local
  },
  data() {
    return {
      showdata: {
        start: ['STOPPED'],
        restart: ['RUNNING'],
        stop: ['RUNNING']
      },
      buttonState: {
        start: ['start'],
        stop: ['stop'],
        restart: ['restart']
      },
      filters: {
        name: '',
        searchType: '1',
        ipAddress: ''
      },
      tableData: [
        {}, {}
      ],
      multipleSelection: [],
      pageSize: 20,
      totalSize: 0,
      currentPage: 1,
      dialogVisible: false,
      options: [
        { label: '删除本地数据', value: 'local' },
        { label: '删除本地以及云数据', value: 'cloud' }
      ],
      deleteType: 'local',
      stompClient: '', // 消息推送,
    }
  },
  mounted() {
    this.getTableData()
    this.connection()
  },
  beforeDestroy: function() {
    this.disconnect()
  },
  computed: {
    currentUser() {
      return this.$store.getters.user
    }
  },
  methods: {
    MysqlSyncStatus(row) {
      const params = {
        id: row.id,
        regionId: row.regionId,
        platformResourceId: row.platformResourceId,
        dataCenterId: row.dataCenterId
      }
      pubRDSApi.MysqlSyncStatus({ params: params }).then((data) => {
        this.getTableData()
      }).catch((error) => {
        this.getTableData()
        self.mloading.hide()
        console.error(error)
      }).then(() => {
      })
    },
    startMysql(row) {
      this.$confirm('确认进行开机操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.id,
          regionId: row.regionId,
          platformResourceId: row.platformResourceId,
          dataCenterId: row.dataCenterId
        }
        pubRDSApi.MySqlStart({ params: params }).then((data) => {
          this.$message({ type: 'success', message: '启动成功' })
          this.getTableData()
          setTimeout(() => {
            this.MysqlSyncStatus(row)
          }, 5000)
        }).catch((error) => {
          self.mloading.hide()
          this.$message({ type: 'success', message: '启动失败' })
          console.error(error)
        }).then(() => {
        })
      })
    },
    stopMysql(row) {
      this.$confirm('确认进行关机操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.id,
          regionId: row.regionId,
          platformResourceId: row.platformResourceId,
          dataCenterId: row.dataCenterId
        }
        pubRDSApi.MySqlStop({ params: params }).then((data) => {
          this.$message({ type: 'success', message: '停止成功' })
          this.getTableData()
          setTimeout(() => {
            this.MysqlSyncStatus(row)
          }, 10000)
        }).catch((error) => {
          self.mloading.hide()
          this.$message({ type: 'success', message: '停止失败' })
          console.error(error)
        }).then(() => {
        })
      })
    },
    restartMysql(row) {
      this.$confirm('确认进行重启操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.id,
          regionId: row.regionId,
          platformResourceId: row.platformResourceId,
          dataCenterId: row.dataCenterId
        }
        pubRDSApi.MySqlRestart({ params: params }).then((data) => {
          this.$message({ type: 'success', message: '重启成功' })
          this.getTableData()
          setTimeout(() => {
            this.MysqlSyncStatus(row)
          }, 5000)
        }).catch((error) => {
          self.mloading.hide()
          this.$message({ type: 'success', message: '重启失败' })
          console.error(error)
        }).then(() => {
        })
      })
    },
    checkResourceState(state, data, operatingButton, buttonState) {
      if (operatingButton.includes(buttonState)) {
        return data.includes(state)
      }
    },
    importInstance() {
      this.$router.push({ name: 'pubImportMysql', params: { previousPage: 'pubMysqlList', routeLevel: 3 } })
    },
    createInstance() {
      this.$router.push({ name: 'pubMysqlCreate', params: { previousPage: 'pubMysqlList', routeLevel: 3 } })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTableData()
    },
    getStateIcon(state, stateName) {
      return pubVmUtil.getVmStateHtml(state, stateName)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData()
    },
    changeSearchType() {
      if (this.filters.searchType == 1) {
        this.filters.ip = ''
      } else if (this.filters.searchType == 2) {
        this.filters.name = ''
      }
    },
    getTableData() {
      const _self = this
      _self.tableData = []
      _self.createDefaultMLoading('#mysqlList')
      _self.mloading.show()
      pubRDSApi.getMysqlList({
        pageNumber: _self.currentPage, pageSize: _self.pageSize, name: _self.filters.name, ip: _self.filters.ipAddress
      }).then((data) => {
        _self.tableData = data.data.pageData
        _self.totalSize = data.data.total
        _self.mloading.hide()
      }).catch((error) => {
        _self.mloading.hide()
        console.log(error)
      })
    },
    clickSearch() {
      this.resetFilterTable()
      this.getTableData()
    },
    openDeleteDialog() {
      this.dialogVisible = true
    },
    resetFilterTable() {
      // 重置页面信息，触发重新加载操作
      this.currentPage = 1
      this.totalSize = 0
      this.pageSize = 10
      this.table.data = []
    },
    clickDelete() {
      const _self = this
      this.$confirm(this.$t('confirm.delete_confirm'), this.$t('confirm.tip'), {
        confirmButtonText: this.$t('btn.ok'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        _self.mloading.show()
        const vmIds = []
        let isLocal = true
        switch (_self.deleteType) {
          case 'local':
            isLocal = true
            break
          case 'cloud':
            isLocal = false
            break
          default:
            break
        }

        for (let i = 0; i < _self.multipleSelection.length; i++) {
          vmIds.push(_self.multipleSelection[i]['id'])
        }
        const params = {
          ids: vmIds,
          local: isLocal
        }

        pubRDSApi.mysqlDeleteRequest({
          params: params
        }).then(() => {
          _self.dialogVisible = false
          _self.$message({type: 'success', message: _self.$t('confirm.delete_success')})
          _self.mloading.hide()
          _self.getTableData()
        }).catch((error) => {
          _self.$message({type: 'error', message: error.msg})
          _self.dialogVisible = false
          _self.mloading.hide()
        })
      })
    },
    connection() {
      const self = this
      messageApi.getMessageUrlRequest().then(({data}) => {
        const socket = new SockJS(data)// 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(socket) // 建立连接对象
        const headers = {Authorization: ''}// 定义客户端的认证信息,按需求配置
        // 向服务器发起websocket连接
        this.stompClient.connect(headers, () => {
          const username = self.currentUser['username']
          this.stompClient.subscribe('/topic/PUB_RDS_MYSQL/' + username, (msg) => { // 订阅服务端提供的某个topic
            this.webSocketMsg(msg)
          }, headers)
        }, (err) => {
          console.log(err)
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    disconnect() {
      // 断开连接
      if (this.stompClient) {
        this.stompClient.disconnect()
      }
    },
    webSocketMsg(msg) {
      const self = this
      const info = JSON.parse(msg.body)
      if (info['eventResult'] === 'SUCCESS') {
        this.$notify({
          title: self.$t('message.success'),
          dangerouslyUseHTMLString: true,
          message: info.eventContent['msgLocal'],
          type: 'success'
        })
        self.getTableData()
      } else {
        this.$notify({
          title: self.$t('message.failed'),
          dangerouslyUseHTMLString: true,
          message: info.eventContent['msgLocal'],
          type: 'error'
        })
      }
    }
  }
}
</script>
